package com.myspace.service.impl.record;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.myspace.mapper.RecordMapper;
import com.myspace.mapper.UserMapper;
import com.myspace.pojo.Record;
import com.myspace.pojo.User;
import com.myspace.service.space.record.AddRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AddRecordServiceImpl implements AddRecordService {
    @Autowired
    private RecordMapper recordMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Map<String, String> addrecord(Integer followId, Integer targetId) {
        QueryWrapper<Record> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("follow_id", followId);
        List<Record> records = recordMapper.selectList(queryWrapper);
        if(records.size() > 0) {
            for(Record record: records) {
                if(targetId.equals(record.getTargetId())) {
                    Map<String, String> map = new HashMap<>();
                    map.put("error_message", "failed");
                    return map;
                }
            }
            Record record = new Record(null, followId, targetId);
            recordMapper.insert(record);
            User user = userMapper.selectById(targetId);
            user.setFollowerCount(user.getFollowerCount() + 1);
            Map<String, String> map = new HashMap<>();
            userMapper.updateById(user);
            map.put("error_message", "success");
            return map;

        }else {
            Record record = new Record(null, followId, targetId);
            recordMapper.insert(record);
            User user = userMapper.selectById(targetId);
            user.setFollowerCount(user.getFollowerCount() + 1);
            Map<String, String> map = new HashMap<>();
            userMapper.updateById(user);
            map.put("error_message", "success");

            return map;
        }

    }
}
